﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using Data;

namespace Bussiness {
    public class HoaDonBanSachService {
        public string CreateMaHoaDonBanSach() {
            HoaDonBanSachRepository res = new HoaDonBanSachRepository();
            return res.CreateMaHoaDonBanSach();
        }

        public int InsertNewHoaDonBanSach(HoaDonBanSachDTO newValue) {
            //kiem 
            HoaDonBanSachRepository res = new HoaDonBanSachRepository();
            return res.InsertNewHoaDonBanSach(newValue);            
        }

        public bool InsertNewHoaDonBanSach(HoaDonBanSachDTO hoaDon, List<ChiTietHoaDonBanSachDTO> chiTietList, KhachHangDTO khachHangDTO, ref string mess) {
#region kiem tra thong tin nhap vao
            int temp = 0;
#region kiem tra thong tin ve khach hang
            //lay thong tin tien no cua khach hang
            KhachHangRepository khRes = new KhachHangRepository();
            int debt = khRes.GetDebt(hoaDon.IDKhachHang);

            //lay tham so
            ThamSoRepository tsRes = new ThamSoRepository();
            temp = tsRes.GetRules(ThamSoRows.NoKhachHang);

            if (debt > temp) {
                mess = "chỉ bán co khách hàng có nợ ko quá " + temp.ToString();
                return false;
            }
#endregion

            //kiem tra thong tin ve phieu thu

#region kiem tra thong tin chi tiet hoa don
            //lay quy dinh ve sach ton [GUI]
                       
            //xem co 2 sach trung nhau ko [GUI]
#endregion

#endregion


            //insert 1 hoa don
            //lay ra ma hoa don moi insert
            int hoaDonID = InsertNewHoaDonBanSach(hoaDon);
            if (hoaDonID == 0) {
                mess = "co loi khi them hoa don ban sach";
                return false;
            }
            //cap nhap lai thong tin chi tiet
            foreach (ChiTietHoaDonBanSachDTO chiTiet in chiTietList) {
                chiTiet.IDHoaDonBanSach = hoaDonID;
            }

            //insert chi tiet
            ChiTietHoaDonBanSachService chiTietSer = new ChiTietHoaDonBanSachService();
            chiTietSer.AddNewBillDetail(chiTietList);

            //cap nhat thong tin khach hang
            //-cap nhat tien no
            khachHangDTO.TienNo = khachHangDTO.TienNo + hoaDon.TongGia;
            KhachHangService khSer = new KhachHangService();
            khSer.UpdateKhachHang(khachHangDTO);
            return true;
        }
    }
}
